package com.interfaces.module.logistics.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.interfaces.module.logistics.domain.FtsLogisticsTrack;
import com.interfaces.module.logistics.service.FtsLogisticsTrackService;
import com.interfaces.module.order.domain.FtsOrder;
import com.interfaces.module.order.service.FtsOrderService;
import com.interfaces.module.user.domain.FtsUserAddress;
import com.interfaces.module.user.service.FtsUserAddressService;
import com.interfaces.util.Result;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.ruoyi.common.logistics.KuaiDi100;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/kuaidi100")
public class KuaiDi100Controller {
    @Autowired
    private FtsOrderService ftsOrderService;
    @Autowired
    private FtsUserAddressService ftsUserAddressService;
    @Autowired
    private FtsLogisticsTrackService ftsLogisticsTrackService;
    /**
     * 快递100接收推送进入的参数
     * @param callbackData
     * @return
     */
    @RequestMapping("/callback")
    public Map callback(@RequestBody JSONObject callbackData){
        String sign=callbackData.getString("sign");
        JSONObject param=callbackData.getJSONObject("param");
        JSONObject lastResult=param.getJSONObject("lastResult");
        String courierNumber=lastResult.getString("nu");
        String logisticsCompany=lastResult.getString("com");
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("courier_number",courierNumber);
        queryWrapper.eq("logistics_company",logisticsCompany);
        ftsLogisticsTrackService.remove(queryWrapper);
        JSONArray datas=lastResult.getJSONArray("data");
        ObjectMapper objectMapper = new ObjectMapper();
        datas.stream().forEach(data->{
            //类型应是物流的记录类型
            FtsLogisticsTrack ftsLogisticsTrack=objectMapper.convertValue(datas, FtsLogisticsTrack.class);
            ftsLogisticsTrack.setLogisticsCompany(logisticsCompany);
            ftsLogisticsTrack.setCourierNumber(courierNumber);
            //进行保存
            ftsLogisticsTrackService.save(ftsLogisticsTrack);
        });
        Map result=new HashMap();
        result.put("result",true);
        result.put("returnCode","200");
        result.put("message","成功");
        return result;
    }

    /**
     * 输入快递公司编码和快递单号进行订阅
     * 也就是发货操作
     * @return
     */
    @Transactional
    @RequestMapping("/subscription")
    public Result subscription(String orderCode,String logisticsCompany,String courierNumber){
        try{
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("order_code",orderCode);
            FtsOrder ftsOrder=ftsOrderService.getOne(queryWrapper);
            ftsOrder.setLogisticsCompany(logisticsCompany);
            ftsOrder.setCourierNumber(courierNumber);
            ftsOrderService.updateById(ftsOrder);
            FtsUserAddress ftsUserAddress=ftsUserAddressService.getById(ftsOrder.getShippingAddressId());

            KuaiDi100 kd100=new KuaiDi100();
            HttpResult result=kd100.subscribeKd100(logisticsCompany,courierNumber,ftsUserAddress.getPhone());
            return Result.SUCCESS(result,"发货成功");
        }catch (Exception e){
            return Result.ERROR("发货失败："+e.getMessage());
        }

    }

    /**
     * 同步最新物流，人为操作,要写在后台管理系统
     * @return
     */
    @RequestMapping("/sycnNewLogistics")
    public Result sycnNewLogistics(String orderCode){
        try{
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("order_code",orderCode);
            FtsOrder ftsOrder=ftsOrderService.getOne(queryWrapper);
            FtsUserAddress ftsUserAddress=ftsUserAddressService.getById(ftsOrder.getShippingAddressId());
            KuaiDi100 kd100=new KuaiDi100();
            HttpResult result=kd100.testQueryTrack(ftsOrder.getLogisticsCompany(),ftsOrder.getCourierNumber(),ftsUserAddress.getPhone());
            if(result.getStatus()==200){
                QueryWrapper queryWrapper1=new QueryWrapper();
                queryWrapper1.eq("courier_number",ftsOrder.getCourierNumber());
                queryWrapper1.eq("logistics_company",ftsOrder.getLogisticsCompany());
                ftsLogisticsTrackService.remove(queryWrapper1);

                JSONObject body=JSONObject.from(result.getBody());
                JSONArray datas =body.getJSONArray("data");
                ObjectMapper objectMapper = new ObjectMapper();
                datas.stream().forEach(data->{
                    //类型应是物流的记录类型
                    FtsLogisticsTrack ftsLogisticsTrack=objectMapper.convertValue(datas, FtsLogisticsTrack.class);
                    //进行保存
                    ftsLogisticsTrack.setOrderCode(orderCode);
                    ftsLogisticsTrack.setLogisticsCompany(ftsOrder.getLogisticsCompany());
                    ftsLogisticsTrack.setCourierNumber(ftsOrder.getCourierNumber());
                    //进行保存
                    ftsLogisticsTrackService.save(ftsLogisticsTrack);
                });
            }
            return Result.SUCCESS("同步成功");
        }catch (Exception e){
            return Result.ERROR("同步失败："+e.getMessage());
        }
    }
}
